﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ClientAppViaWebService.BaseLogicServiceRef;

namespace ClientAppViaWebService.DBAdministration
{
    public partial class RuleInsertAdministartionForm : Form
    {
        public string SelectedDataBase;
        private BaseLogicService service = new BaseLogicService();
        private InsertRule[] originalDataSource;
        private TClass[] classes;
        private Boolean changesMade = false;

        public RuleInsertAdministartionForm()
        {
            InitializeComponent();

            cmbDatabases.DataSource = service.SelectAvailableDataBases();
            classes = service.SelectTClassListByDataBaseName(SelectedDataBase);
        }

        private void cmbDatabases_SelectedIndexChanged(object sender, EventArgs e)
        {
            SelectedDataBase = cmbDatabases.SelectedValue.ToString();
            dtgRuleInsert.Rows.Clear();

            classes = service.SelectTClassListByDataBaseName(SelectedDataBase);

            originalDataSource = service.SelectTRuleInsertListByDataBaseName(SelectedDataBase);

            List<string> classesList = (from c in classes select c.NAME).ToList();
            classesList.Insert(0,"University");

            pClassCol.DataSource = cClassCol.DataSource = classesList;

            foreach (InsertRule ins in originalDataSource)
            {
                Int32 idx = dtgRuleInsert.Rows.Add();
                dtgRuleInsert.Rows[idx].Cells["pClassCol"].Value = ((DataGridViewComboBoxCell)dtgRuleInsert.Rows[idx].Cells["pClassCol"]).Items[ins.PARENT_CLASS_ID];
                dtgRuleInsert.Rows[idx].Cells["cClassCol"].Value = ((DataGridViewComboBoxCell)dtgRuleInsert.Rows[idx].Cells["cClassCol"]).Items[ins.CHILD_CLASS_ID];
                dtgRuleInsert.Rows[idx].Cells["idColumn"].Value = ins.ID;
            }
            changesMade = false;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!changesMade)
            {
                return;
            }

            foreach (DataGridViewRow row in dtgRuleInsert.Rows)
            {
                Boolean dup = false;
                if (row.Cells["pClassCol"].Value != null && row.Cells["cClassCol"].Value != null)
                {
                    for (Int32 i = 0; i < row.Index; ++i)
                    {
                        if (dtgRuleInsert.Rows[i].Cells["pClassCol"].Value.Equals(row.Cells["pClassCol"].Value)
                            && dtgRuleInsert.Rows[i].Cells["cClassCol"].Value.Equals(row.Cells["cClassCol"].Value))
                        {
                            row.Visible = false;
                            changesMade = true;
                            dup = true;
                            break;
                        }
                    }
                    if (!dup)
                    {
                        //Inserted
                        if (row.Cells["idColumn"].Value == null)
                        {
                            service.InsertTRuleInsert(new InsertRule
                            {
                                PARENT_CLASS_ID = ((DataGridViewComboBoxCell)row.Cells["pClassCol"]).Items.IndexOf(row.Cells["pClassCol"].Value),
                                CHILD_CLASS_ID = ((DataGridViewComboBoxCell)row.Cells["cClassCol"]).Items.IndexOf(row.Cells["cClassCol"].Value),
                                DataBaseName = SelectedDataBase
                            });
                        }
                        //Updated
                        else if (row.Tag != null && row.Tag.ToString() == "Edited"
                           && row.Cells["idColumn"].Value != null)
                        {
                            service.UpdateTRuleInsert(new InsertRule
                            {
                                ID = int.Parse(row.Cells["idColumn"].Value.ToString()),
                                PARENT_CLASS_ID = ((DataGridViewComboBoxCell)row.Cells["pClassCol"]).Items.IndexOf(row.Cells["pClassCol"].Value),
                                CHILD_CLASS_ID = ((DataGridViewComboBoxCell)row.Cells["cClassCol"]).Items.IndexOf(row.Cells["cClassCol"].Value),
                                DataBaseName = SelectedDataBase
                            });
                        }
                    }
                }
                //Deleted
                if (row.Visible == false && row.Cells["idColumn"].Value != null)
                {
                    service.DeleteTRuleInsert(new InsertRule
                    {
                        ID = int.Parse(row.Cells["idColumn"].Value.ToString())
                        ,
                        DataBaseName = SelectedDataBase
                    });
                }
            }
            if (changesMade)
            {
                MessageBox.Show(this, "Changes were saved successfully", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                changesMade = false;
            }
        }

        private void dtgRuleInsert_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
        {
            e.Row.Visible = false;
            dtgRuleInsert.Rows.Add(e.Row);
            changesMade = true;
        }

        private void dtgRuleInsert_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            dtgRuleInsert.Rows[e.RowIndex].Tag = "Edited";
            changesMade = true;
        }

        private void dtgRuleInsert_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            MessageBox.Show(this, "Bad thing happened!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private void dtgRuleInsert_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            // Delete clicked
            if (e.ColumnIndex == 3 && (e.RowIndex != dtgRuleInsert.Rows.Count - 1))
            {
                if (MessageBox.Show(this, "Delete relation?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    dtgRuleInsert.Rows[e.RowIndex].Visible = false;
                    changesMade = true;
                }
            }
        }

        private void dtgRuleInsert_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(RuleInsertAdministartionForm));
            dtgRuleInsert.Rows[e.RowIndex].Cells["delColumn"].Value = ((System.Drawing.Image)(resources.GetObject("delColumn.Image")));
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }    
      
    }
}
